//
//  NetWorkTools.swift
//  AFN swift
//
//  Created by mac on 16/1/23.
//  Copyright © 2016年 tingyuyisheng. All rights reserved.
//

import UIKit
import AFNetworking
/// HTTP请求方法
///
/// - GET:  GET
/// - POST: POST
enum YDFrequestMethod: String {

	case GET = "GET"
	case POST = "POST"
}

/// 网络工具
class NetWorkTools: AFHTTPSessionManager {

	// MARK: - 应用程序信息
	/// 应用程序 ID
	private let appKey = "3851778136"
	/// 应用程序秘钥
	private let appSecret = "498f0d4864637ad66ae29df7bf55e19d"
	/// OAuth 重定向地址
	private let redirectUri = "http://www.baidu.com"
	/// 请求的类型
	private let grant_type = "authorization_code"
    
    typealias YDFrequestCallBack = (result: AnyObject?, error: NSError?)->()

	static let sharedTools : NetWorkTools = {

		let tools = NetWorkTools(baseURL: nil)
		// 设置反序列化
		tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
		return tools
	}()
}

// MARK: - 封装OAuth方法
extension NetWorkTools {

	/// OAuth授权URL
	/// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
	var oauthURL : NSURL {

		let URLString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUri)"
		return NSURL(string: URLString)!
	}
    
    

    /// 加载AccessToken
    ///
    /// - parameter code:     授权码
    /// - parameter finished: 完成回调
    /// - see: [http://open.weibo.com/wiki/OAuth2/access_token](http://open.weibo.com/wiki/OAuth2/access_token)
    func loadAccessToken(code: String,finished:YDFrequestCallBack) {

		let urlstring = "https://api.weibo.com/oauth2/access_token"

		let parameters = ["client_id": appKey,
			"client_secret": appSecret,
			"grant_type": grant_type,
			"code": code,
			"redirect_uri": redirectUri,]
        request(.POST, URLString: urlstring, parameters: parameters, finished: finished)
	}
}

// MARK: - 封装AFN网络方法
extension NetWorkTools {

	/// 网络请求
	///
	/// - parameter method:     GET/POST
	/// - parameter URLString:  地址
	/// - parameter parameters: 参数
	/// - parameter finished:   成功或者失败回调
    private func request(method: YDFrequestMethod, URLString: String, parameters: [String : AnyObject]?, finished: YDFrequestCallBack) {

		/// 定义成功的回调
		let success = { (task: NSURLSessionDataTask, result: AnyObject?) -> Void in

			finished(result: result, error: nil)
		}
		/// 定义失败的回调
		let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in

			print(error)
			finished(result: nil, error: error)
		}

		if method == .GET {

			GET(URLString, parameters: parameters, progress: { (_) -> Void in
				}, success: success, failure: failure)
		} else {

			POST(URLString, parameters: parameters, progress: { (_) -> Void in
				}, success: success, failure: failure)
		}
	}
}